package com.rinlink.jbcodec.creator;



import com.alibaba.fastjson.JSONObject;
import com.rinlink.jbcodec.JSONCodec;
import com.rinlink.jbcodec.TransformCreator;
import com.rinlink.jbcodec.context.ObjectToBytesCreatorContext;
import com.rinlink.jbcodec.exception.CreateTransformException;
import com.rinlink.jbcodec.transform.Transform;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class ObjectToBytesCreator<T> implements TransformCreator<byte[], ObjectToBytesCreatorContext> {

     private Class<T> objectClass;


    public ObjectToBytesCreator() {
        Type type = this.getClass().getGenericSuperclass();
        ParameterizedType ptype=(ParameterizedType)type;
        Type[] types = ptype.getActualTypeArguments();
        this.objectClass = (Class) types[0];
    }

    public ObjectToBytesCreator(Class<T> t){
        this.objectClass = t;
    }

    @Override
    public Transform<byte[]> create(int fieldIndex,ObjectToBytesCreatorContext ctx) {
        JSONCodec.Field field = ctx.getScheme().getFields().get(fieldIndex);
        JSONObject sourceData =  ctx.getSourceData();
        JSONObject attr = field.getAttr();
        String fieldName = field.getName();
        T value;
        try {
            value = sourceData.getObject(fieldName,objectClass);
        }catch (ClassCastException e){
            throw new CreateTransformException("类型不匹配");
        }

        return create(value,attr == null ? new JSONObject() : attr, sourceData);
    }

    protected abstract Transform<byte[]> create(T t, JSONObject attr, JSONObject source);

}
